package com.tong.embeddedvr.filter;

import com.tong.embeddedvr.utils.CommonUtil;
import org.apache.logging.log4j.ThreadContext;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(urlPatterns = "/statistic/*",filterName = "statisticFilter")
public class StatisticFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setHeader("Access-Control-Allow-Credentials", "true");
        //允许对应的源
        response.setHeader("Access-Control-Allow-Origin",request.getHeader("origin"));
        //对session放行
        response.setHeader("Set-Cookie","HttpOnly;Secure;SameSite=None");
        HttpSession session = ((HttpServletRequest) servletRequest).getSession();
        //取session的前10位作为日志的标记
        ThreadContext.put("logId", CommonUtil.getRandomString(10));
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}
